﻿using IdentityModel.Client;
using System;
using System.Net.Http;

namespace Revice.Client
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                RequestTestAsync()
                    .Wait();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.WriteLine("Hello World!");
            Console.ReadKey();
        }

        private static async System.Threading.Tasks.Task RequestTestAsync()
        {
            var disco = await DiscoveryClient.GetAsync("http://localhost:5000");
            if (disco.IsError)
            {
                Console.WriteLine(disco.Error);
                return;
            }
            //var tokenClient = new TokenClient(disco.TokenEndpoint, "client", "p@ssw0rd");
            //var tokenResponse = await tokenClient.RequestClientCredentialsAsync();
            var tokenClient = new TokenClient(disco.TokenEndpoint, "passwordClient", "p@ssw0rd");
            var tokenResponse = await tokenClient.RequestResourceOwnerPasswordAsync("admin","p@ssw0rd");
            if (tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);
                return;
            }

            var httpClient = new HttpClient();
            httpClient.SetBearerToken(tokenResponse.AccessToken);
            var response = await httpClient.GetAsync("http://localhost:5001/api/values/get");
            if (response.IsSuccessStatusCode)
            {
                var content = await response.Content.ReadAsStringAsync();
                Console.WriteLine(content);
            }
        }
    }
}
